package com.wzj.yygh.cmn.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.yygh.cmn.listener.DictListener;
import com.wzj.yygh.cmn.mapper.DictMapper;
import com.wzj.yygh.cmn.service.DictService;
import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.model.cmn.Dict;
import com.wzj.yygh.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@SuppressWarnings("all")
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private RedisTemplate redisTemplate;
    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict",key = "#id")
    public List<Dict> findChlidData(Long id) {
        //先从缓存中查询数据
        List<Dict> dictList =(List<Dict>) redisTemplate.opsForValue().get("dictList:" + id);

        if (dictList != null) {
            return dictList;
        }
        //如果没有从缓存中获取
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict:dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        //先存入缓存中
        try {
            redisTemplate.opsForValue().set("dictList:" + id,dictList);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return dictList;
    }
    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Long count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count>0;
    }

    //导出数据字典接口
    @Override
    public List<DictEeVo> exportDictData() {
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //Dict -- DictEeVo
        List<DictEeVo> dictVoList = new ArrayList<>();
        for(Dict dict:dictList) {
            DictEeVo dictEeVo = new DictEeVo();
           // dictEeVo.setId(dict.getId());
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);
        }
        return dictVoList;
    }

    //导入数据字典
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importDictData(MultipartFile file) {
        try {
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            // 这里每次会读取100条数据 然后返回过来 直接调用使用数据就行
//            EasyExcel.read((File) file, DictEeVo.class, new DictListener()).sheet().doRead();
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(ResultCode.ERROR,"文件上传失败",e);
        }
    }

    //根据dictcode和value查询
    @Override
    public String getNameByparentDictCodeAndValue(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if(StringUtils.isEmpty(dictCode)) {
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {//如果dictCode不为空，根据dictCode和value查询
            //根据dictcode查询dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parent_id = codeDict.getId();
            //根据parent_id和value进行查询
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return finalDict.getName();
        }
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    //根据dictCode获取下级节点
    @Override
    @Cacheable(value = "dict",key = "#dictCode")
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        if (dict == null) throw new YyghException("数据不存在",ResultCode.ERROR_NO_DATA);
        //根据id获取子节点
        List<Dict> chlidData = this.findChlidData(dict.getId());

        return chlidData;
    }


}
